import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_easy_permission/easy_permissions.dart';
import 'package:flutter_scankit/flutter_scankit.dart';
import 'package:flutter_yishop/constants/Constants.dart';
import 'package:flutter_yishop/model/BannerModel.dart';
import 'package:flutter_yishop/utils/screen/ScreenAdapter.dart';
import 'package:flutter_swiper/flutter_swiper.dart';
import 'package:flutter_yishop/utils/toast_util.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:sp_util/sp_util.dart';

import '../../config/Config.dart';
import '../../config/StorageManager.dart';
import '../../config/StorageManager.dart';
import '../../model/HotProductsModel.dart';

class Home extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return _Home();
  }
}

const _permissions = const [
  Permissions.READ_EXTERNAL_STORAGE,
  Permissions.CAMERA
];

const _permissionGroup = const [PermissionGroup.Camera, PermissionGroup.Photos];

class _Home extends State<Home> with AutomaticKeepAliveClientMixin {
  List _bannersData = [];
  List _productData = [];
  List _hotProductData = [];

  FlutterScankit scanKit;
  String code = "";

  @override
  void initState() {
    scanKit = FlutterScankit();
    scanKit.addResultListen((val) {
      debugPrint("scanning result:$val");
      setState(() {
        code = val ?? "";
        ToastUtil.showToasts("扫码：$code");
      });
    });

    FlutterEasyPermission().addPermissionCallback(
        onGranted: (requestCode, perms, perm) {
          startScan();
        },
        onDenied: (requestCode, perms, perm, isPermanent) {});

    //获取轮播图数据
    _getBannersData();
    //获取猜你喜欢数据
    _getProductData();
    //获取热门推荐数据
    _getHotProductData();

    print("home");

    List list = SpUtil.getStringList(Constants.SEARCHLIST);
    print('list:${list.reversed}');
  }

  @override
  // TODO: implement wantKeepAlive
  bool get wantKeepAlive => true;

  Future<void> startScan() async {
    try {
      await scanKit.startScan(scanTypes: [ScanTypes.ALL]);
    } on PlatformException {}
  }

  //获取轮播图数据
  _getBannersData() async {
    var api = '${Config.url}api/focus';
    var bannersData = await Dio().get(api);
    var focusList = BannerModel.fromJson(bannersData.data);

    setState(() {
      this._bannersData = focusList.result;
    });
  }

  //获取猜你喜欢数据
  _getProductData() async {
    var api = '${Config.url}api/plist?is_hot=1';
    var productData = await Dio().get(api);
    var productList = HotProductsModel.fromJson(productData.data);

    setState(() {
      this._productData = productList.result;
    });
  }

  //获取热门推荐数据
  //2020-11-25
  //(•́へ•́╬)愤怒
  //破接口，竟然 price 这个参数出现了int 和 string 类型，搞了我大白天才看出来~~~~
  //2020-11-27
  //改成 Object
  _getHotProductData() async {
    var api = '${Config.url}api/plist?is_best=1';
    var hotProductData = await Dio().get(api);
    var hotProductList = HotProductsModel.fromJson(hotProductData.data);

    setState(() {
      this._hotProductData = hotProductList.result;
    });
  }

  //轮播图
  Widget _swiperWidget(value) {
    if (value.length > 0) {
      return Container(
        child: AspectRatio(
          aspectRatio: 2 / 1,
          child: new Swiper(
            autoplay: true,
            duration: 300,
            itemBuilder: (BuildContext context, int index) {
              String pic = value[index].pic;
              return new Image.network(
                "${Config.url}${pic.replaceAll("\\", "/")}",
                fit: BoxFit.cover,
              );
            },
            itemCount: value.length,
            pagination: new SwiperPagination(),
            onTap: (index) {
              String pic = value[index].pic;
              String title = value[index].title;
              Navigator.pushNamed(context, Constants.BANNER, arguments: {
                "url": "${Config.url}${pic.replaceAll("\\", "/")}",
                "title": title
              });
            },
          ),
        ),
      );
    } else {
      return Text("加载中...");
    }
  }

  //标题
  Widget _titleWidget(value) {
    return Container(
      margin: EdgeInsets.all(ScreenAdapter.width(15)),
      decoration: BoxDecoration(
          border: Border(
              left: BorderSide(
        color: Colors.redAccent,
        width: ScreenAdapter.width(8),
      ))),
      child: Padding(
        padding: EdgeInsets.fromLTRB(ScreenAdapter.width(10), 0, 0, 0),
        child: Text(
          value,
          style: TextStyle(
            color: Colors.black54,
          ),
        ),
      ),
    );
  }

  //猜你喜欢内容
  Widget _contentWidget(List value) {
    if (value.length > 0) {
      return Container(
        margin: EdgeInsets.only(right: ScreenAdapter.width(20)),
        height: ScreenAdapter.height(260),
        child: ListView.builder(
          itemCount: value.length,
          scrollDirection: Axis.horizontal,
          itemBuilder: (context, index) {
            String pic = value[index].pic;
            return GestureDetector(
              child: Container(
                margin: EdgeInsets.fromLTRB(
                    ScreenAdapter.width(20), ScreenAdapter.width(10), 0, 0),
                child: Column(
                  children: <Widget>[
                    Image.network(
                      "${Config.url}${pic.replaceAll("\\", "/")}",
                      fit: BoxFit.cover,
                      width: ScreenAdapter.width(180),
                      height: ScreenAdapter.height(180),
                    ),
                    SizedBox(
                      height: ScreenAdapter.height(20),
                    ),
                    Container(
                      width: 90,
                      child: Center(
                        child: Text(
                          "￥${value[index].price}",
                          maxLines: 1,
                          overflow: TextOverflow.ellipsis,
                          style: TextStyle(color: Colors.redAccent),
                        ),
                      ),
                    )
                  ],
                ),
              ),
              onTap: () {
                Navigator.pushNamed(context, Constants.PRODUCTCONTENT,
                    arguments: {"id": "${value[index].id}"});
              },
            );
          },
        ),
      );
    } else {
      return Text("加载中...");
    }
  }

  //推荐商品
  Widget _recProductListWidget(value) {
    var itemWidth = (ScreenAdapter.getScreenWith() - 30) / 2;
    //图片
    String sPic = value.pic;
    sPic = Config.url + sPic.replaceAll('\\', '/');
    return GestureDetector(
      child: Container(
        padding: EdgeInsets.all(5),
        width: itemWidth,
        decoration:
            BoxDecoration(border: Border.all(color: Colors.black12, width: 1)),
        child: Column(
          children: <Widget>[
            Container(
              width: double.infinity,
              child: AspectRatio(
                aspectRatio: 1 / 1,
                child: Image.network(
                  "${sPic}",
                  fit: BoxFit.cover,
                ),
              ),
            ),
            Padding(
              padding: EdgeInsets.fromLTRB(
                  0, ScreenAdapter.height(10), 0, ScreenAdapter.height(10)),
              child: Text(
                "${value.title}",
                maxLines: 2,
                overflow: TextOverflow.ellipsis,
                style: TextStyle(
                  color: Colors.black54,
                ),
              ),
            ),
            Padding(
              padding: EdgeInsets.only(bottom: ScreenAdapter.height(10)),
              child: Stack(
                children: <Widget>[
                  Align(
                    alignment: Alignment.centerLeft,
                    child: Text(
                      "¥${value.price}",
                      style: TextStyle(color: Colors.redAccent, fontSize: 16),
                    ),
                  ),
                  Align(
                    alignment: Alignment.centerRight,
                    child: Text(
                      "¥${value.oldPrice}",
                      style: TextStyle(
                          color: Colors.black54,
                          fontSize: 14,
                          decoration: TextDecoration.lineThrough),
                    ),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
      onTap: () {
        Navigator.pushNamed(context, Constants.PRODUCTCONTENT,
            arguments: {"id": "${value.id}"});
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    super.build(context);
    ScreenAdapter.init(context);
    return Scaffold(
      appBar: _appBarWidget(),
      body: ListView(
        children: <Widget>[
          _swiperWidget(this._bannersData),
          _titleWidget("猜你喜欢"),
          _contentWidget(this._productData),
          _titleWidget("热门推荐"),
          Container(
            padding: EdgeInsets.all(10),
            child: Wrap(
              runSpacing: 10,
              spacing: 10,
              children: this._hotProductData.map((value) {
                return _recProductListWidget(value);
              }).toList(),
            ),
          ),
        ],
      ),
    );
  }

  Widget _appBarWidget() {
    return AppBar(
      leading: IconButton(
        icon: Icon(
          Icons.center_focus_weak,
          color: Colors.black87,
        ),
        onPressed: () async{
          if (!await FlutterEasyPermission.has(
              perms: _permissions, permsGroup: _permissionGroup)) {
            FlutterEasyPermission.request(
                perms: _permissions, permsGroup: _permissionGroup);
          } else {
            startScan();
          }
        },
      ),
      actions: <Widget>[
        IconButton(
          icon: Icon(
            Icons.message,
            color: Colors.black87,
          ),
          onPressed: () {
            ToastUtil.showToasts("消息");
          },
        ),
      ],
      // backgroundColor: Colors.redAccent,
      title: InkWell(
        child: Container(
          padding: EdgeInsets.fromLTRB(
              ScreenAdapter.width(20),
              ScreenAdapter.width(8),
              ScreenAdapter.width(20),
              ScreenAdapter.width(8)),
          child: Row(
            children: <Widget>[
              Icon(
                Icons.search,
                color: Colors.black38,
                size: 20,
              ),
              SizedBox(
                width: ScreenAdapter.width(30),
              ),
              Text(
                "笔记本",
                style: TextStyle(
                    color: Colors.black38, fontSize: ScreenAdapter.size(25)),
              ),
            ],
          ),
          decoration: BoxDecoration(
              borderRadius: BorderRadius.all(Radius.circular(15)),
              color: Colors.black12),
        ),
        onTap: () {
          Navigator.of(context).pushNamed(Constants.SEARCH);
        },
      )
      // Text(_pageTitle[this._currentIndex])
      ,
      elevation: 0,
    );
  }

  @override
  void dispose() {
    scanKit.dispose();
    super.dispose();
  }
}
